<?php
/* explain:		user class
 * Project:     
 * File:        Users.php
 *
 * @ link 		http://www.../lib/
 * @ Email		ldmmyx@hotmail.com
 * @ copyright 	2007  Ling Deming
 * @ author 	Ivan  Ling Deming
 * @ version 2.0
 *
 */
include_once(dirname(__FILE__) . '/../utils/CommonUtils.php');
require_once(dirname(__FILE__) . '/../domain/UserDomain.php');
					//--> Strings
class UserImpl extends CommonUtils
{
	
	function __construct($DBTag = 'system')
	{
		parent::__construct();
		
		$this->DBTag = $DBTag;
	}
	
	/* get user info ( default id)
	 *
	 * @ param  string id
	 * @ param  return array
	 */
	public function get($id)
	{		
		$sql = "SELECT groupid, name, password, email, status, regtime FROM users WHERE id = $id";
		
		$obj = null;
		$conn = null;
		
		try {
			$conn = $this->getConnection($this->DBTag);
			
			$rs = mysql_query($sql, $conn);
			if ($row = mysql_fetch_row($rs)) {
				$obj = new UserDomain();

				$obj->setId($id);
				$obj->setGroupId($row[0]);
				$obj->setName($row[1]);				
				$obj->setPassword($row[2]);
				$obj->setEmail($row[3]);
				$obj->setStatus($row[4]);
				$obj->setRegtime($row[5]);
				
			} else {
				$this->message = "get data failed by Id. sql : $sql <br>";
				$this->message .= "error: " . mysql_error($conn);
			}
		} catch (Exception $e) {
			$this->message = $e->getMessage();
		}
		
		$this->freeConnection($this->DBTag, $conn);
			
		return $obj;
	}

	/* get user info
	 *
	 * @ param  string username  
	 * @ param  return array     
	 */
	public function getByEmail($email)
	{
		$sql = "SELECT groupid, id, password, name, status, regtime FROM users WHERE email = '$email'";
		
		$obj 	= null;
		$conn 	= null;
		
		try {
			$conn = $this->getConnection($this->DBTag);
			
			$rs = mysql_query($sql, $conn);
			if ($row = mysql_fetch_row($rs)) {
				$obj = new UserDomain();
				
				$obj->setEmail($email);
				
				$obj->setGroupId($row[0]);
				$obj->setId($row[1]);
				$obj->setPassword($row[2]);
				
				$obj->setName($row[3]);	
				$obj->setStatus($row[4]);
				$obj->setRegtime($row[5]);				
				
			} else {
				$this->message = "get data failed by Id. sql : $sql <br>";
				$this->message .= "error: " . mysql_error($conn);
			}
		} catch (Exception $e) {
			$this->message = $e->getMessage();
		}
		
		$this->freeConnection($this->DBTag, $conn);
			
		return $obj;
	}
	
	/* add user
	 *
	 * @ param  return boolean user object
	 */
	public function add($obj)
	{		
		if($obj instanceof UserDomain){
			$strPassword 	= md5($obj->getPassword() . PopedomUtils::SYSTEM_SAFE_KEY);
			$strSafeid 		= md5(PopedomUtils::SYSTEM_SAFE_KEY. $obj->getGroupId() . $obj->getEmail() . $strPassword . $obj->getStatus());
			
			$sql 	 = "INSERT INTO users SET regtime = UTC_TIMESTAMP(), name='";
			$sql	.= addslashes($obj->getName());
			
			$sql 	.= "', groupid='";
			$sql	.= $obj->getGroupId();	
	
			$sql 	.= "', email='";
			$sql	.= addslashes($obj->getEmail());
	
			$sql 	.= "', password='";
			$sql	.= $strPassword;

			$sql	.= "', status='";
			$sql	.= $obj->getStatus();
			
			$sql	.= "', safeid='$strSafeid";
			
			$sql	.= "' ON DUPLICATE KEY UPDATE groupid=Values(groupid), name=Values(name), email=Values(email), password=Values(password)";
			$sql	.= ", status=Values(status)";
			
			$id = $this->insert($this->DBTag, $sql);
			
			$obj->setId($id);
		}else{
			$id	= -1;
			
			$this->message = 'input object is not instance of UserDomain.';
		}
		
		return $id;
	}
	
	/* edit user
	 *
	 * @ param  string obj     user domain
	 * @ param  return boolean  	true??? update success,  false???update fail
	 */
	public function edit($obj)
	{
		if($obj instanceof UserDomain){
			$strPassword 	= md5($obj->getPassword());
			$strSafeid 		= md5(PopedomUtils::SYSTEM_SAFE_KEY. $obj->getGroupId() . $obj->getName() . $strPassword . $obj->getStatus());
			
			$sql 	 = "INSERT INTO users SET regtime = UTC_TIMESTAMP(), name='";
			$sql	.= addslashes($obj->getName());
						
			$sql 	.= "', id='";
			$sql	.= $obj->getId();
			
			$sql 	.= "', groupid='";
			$sql	.= $obj->getGroupId();	
	
			$sql 	.= "', email='";
			$sql	.= addslashes($obj->getEmail());
	
			$sql 	.= "', password='";
			$sql	.= $strPassword;

			$sql	.= "', status='";
			$sql	.= $obj->getStatus();
			
			$sql	.= "', safeid='$strSafeid";
			
			$sql	.= "' ON DUPLICATE KEY UPDATE groupid=Values(groupid), name=Values(name), email=Values(email), password=Values(password)";
			$sql	.= ", status=Values(status)";
			
			$id = $this->insert($this->DBTag, $sql);
			
			$obj->setId($id);
		}else{
			$id	= -1;
			
			$this->message = 'input object is not instance of UserDomain.';
		}
	}
	
	/* user list
	 *
	 * @ param  string 	where   	a?? where condition
	 * @ param  string 	page   		a?? curent page
	 * @ param  string 	discount   	a?? display data count
	 * @ param  string 	url   		a?? user url
	 * @ param  return 	array		a?? data array
	 */
	public function lists($arrPopedom = array(), $where, $page = '', $discount = '', $url = '')
	{
		if($this->isUnallowable($arrPopedom, PopedomUtils::STRING_VIEW))
			die ($this->getNotPopedomInfo());

		$this->objLog->addOperate($this->iUserID, __METHOD__, PopedomUtils::STRING_VIEW);
		
		$arrback = array();
	
		$sql = "SELECT count(id) FROM users $where";
		$rs  = mysql_query($sql,$this->conHandle) or die(mysql_error());
		
		list($total) = mysql_fetch_row($rs);
		$this->mutilPager($total, $page, $discount, $url);
		if(empty($total))
 			return $arrback;

		if(empty($discount))
			$sql = "SELECT * FROM users $where";
		else{
			$sql = "SELECT * FROM users $where LIMIT $this->firstcount, $discount";
		}
	
		$rs  = mysql_query($sql,$this->conHandle);
		if($rs){
			while(is_array($arrtmp = mysql_fetch_array($rs))){
				$arrback[] = $arrtmp;
			}
			return $arrback;
		}else
 			return $arrback;
	}
	
	/* delete user
	 *
 	 * @ param  int    userid
	 * @ param  return boolean
	 */
	public function delete($id)
	{
		$sql = "DELETE FROM users WHERE id = $id";
		
		return $this->update($this->DBTag, $sql);
	}
	
	public function IsExistByEmail($email)
	{
		$sql = "SELECT id FROM users WHERE email = '$email'";
		
		return $this->isExisted($this->DBTag, $sql);
	}

	public function autoLoginName($namecnUTF8)
	{
		$objString 	= new Strings();	//--> Strings
		$pinyuin = $objString->Pinyin($namecnUTF8, 'UTF-8');
		
		$i = 0;
		while($this->IsExistFromName($pinyuin)){
			$pinyuin .= $i;
			
			$i++;
		}
		
		return $pinyuin;
	}
	
	/* edit user status
	 *
 	 * @ param  int    userid
	 * @ param  string status	
	 * @ param  return boolean
	 */
	public function editStatus($obj)
	{
		$strPassword 	= md5($obj->getPassword());
		$strSafeid 	= md5(PopedomUtils::SYSTEM_SAFE_KEY. $obj->getGroupId() . $obj->getName() . $strPassword . $obj->getStatus());
		
		$sql = "UPDATE users SET status='$status', safeid='$strSafeid' WHERE id=$id";
		
		return $this->update($this->DBTag, $sql);			
	}

	/* edit user status
	 *
 	 * @ param  int    userid
	 * @ param  string status	
	 * @ param  return boolean
	 */
	public function editStatusAddBalance($id, $status, $platform, $balance)
	{
		$arrUserInfo = $this->get($id);
		$strSafeid 	 = md5(PopedomUtils::SYSTEM_SAFE_KEY.$arrUserInfo['groupid'].$arrUserInfo['name'].$arrUserInfo['password'].$status);

		$sql = 'set session autocommit=false';
		$rs = mysql_query($sql, $this->conHandle) or die (mysql_error());
		
		$sql = 'start transaction';
		$rs = mysql_query($sql, $this->conHandle) or die (mysql_error()); 
		
		$sql = "UPDATE users SET status='$status', safeid='$strSafeid' WHERE id=$id";
		$rs	 = mysql_query($sql,$this->conHandle);
		if(mysql_affected_rows($this->conHandle) > 0){
			$sql = "SELECT balance FROM account WHERE userid = $id";
			$rs  = mysql_query($sql, $this->conHandle);
		
			if($rs && mysql_num_rows($rs) > 0){
				return true;
			}else{
				$sql = "INSERT INTO account SET userid='$id', platform='$platform', balance='$balance', status='approved'";
				
				$rs  = mysql_query($sql, $this->conHandle) or die (mysql_error($this->conHandle));
				
				if($rs){
					$sql = 'commit';
					$rs = mysql_query($sql, $this->conHandle) or die (mysql_error()); 
					if(!$rs){
						$sql = 'rollback';
						$rs = mysql_query($sql, $this->conHandle);
					}
				}else{
					$sql = 'rollback';
					$rs = mysql_query($sql, $this->conHandle);
				}
			}
			
			return true;
		}else{
			$sql = 'rollback';
			$rs = mysql_query($sql, $this->conHandle);
				
			return false;
		}
			
	}
	
	/* check all data is safe
	 *
	 * @ param  string safe_key
	 * @ param  return invalid fail user ID array.
	 */
	public function checkAllSafeKey($safe_key)
	{
		$arrback = array();
		if(empty($safe_key))
 			return 0;

		$sql = "SELECT id, groupid, name, password, status, safeid FROM users WHERE status = 'normal'";
		$rs	 = mysql_query($sql, $this->conHandle);
		if($rs){
			while(list($id,$groupid,$name,$password,$status,$safeid) = mysql_fetch_row($rs)){
				if($safeid != md5($safe_key.$groupid.$name.$password.$status)){
					$arrback[] = $id;
				}
			}
		}
		return $arrback;
	}

	/* check only user data is safe
	 *
	 * @ param  int 	userid     	user id
	 * @ param  string 	safe_key    security key
	 * @ param  return 	mix  		-1: invalid parameter???0: valid fail???1??? valid success
	 */
	public function checkUserSafe($userid)
	{
		if(empty($userid))
 			return false;

		$sql 	= "SELECT safeid, groupid, email, password, status FROM users WHERE id = $userid";
		$conn 	= null;
		
		try {
			$conn 	= $this->getConnection($this->DBTag);			
			$rs	 	= mysql_query($sql, $conn);
			if($rs){
				list($safeid, $groupid, $email, $password, $status) = mysql_fetch_row($rs);
	
				if($safeid == md5(PopedomUtils::SYSTEM_SAFE_KEY . $groupid . $email. $password. $status))
					return true;
				else
					return false;
			}
		} catch (Exception $e) {
			$this->message = $e->getMessage();
		}
		
		$this->freeConnection($this->DBTag, $conn);	
			
		return false;
	}
	
	public function arrGetUserList()
	{
		$sql = "SELECT id, name FROM users WHERE status = 'normal' AND id != 1";
		
		$rs = mysql_query($sql, $this->conHandle);
		
		$arrCache = array();
		if($rs){
			while ($arrData = mysql_fetch_array($rs)){
				$arrCache[$arrData['id']] = $arrData['name'];
			}
		}
		return $arrCache;
	}
}
?>
